extends Node
class_name State_Machine
# 可以外部指定默认的初始状态
@export var initial_state: State;

var current_state:State;
var states:Dictionary = {}

func _ready() -> void:
	# 所有的状态节点都会挂在到当前节点下，然后存到一个字典中
	for child in get_children():
		if child is State:
			states[child.name.to_lower()] = child
			# 将 actor 的引用注入到每一个 state 中
			child.actor = get_parent()
			# 如果子状态有 init_state 方法，就调用它
			child.state_machine = self # 传递 FSM 引用
			
#			State 链接信号 到状态机的on_child_transionn方法来触发
			child.Transitioned.connect(on_child_transionn)

	# 如果指定了初始状态，就设置为当前状态和执行 Enter
	if initial_state:
		current_state = initial_state
		initial_state.Enter()

func _process(delta: float) -> void:
	if current_state:
		current_state.Update(delta)

func _physics_process(delta: float) -> void:
	if current_state:
		current_state.Physic_Update(delta)


func on_child_transionn(from: String,to: String):
	if from == to:
		return
	var newState = states.get(to.to_lower()) as State
	if !newState:
		return
	if current_state:
		current_state.Exit()
	current_state = newState
	newState.Enter()
